﻿using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Newtonsoft.Json.Linq;
using Terraria.GameContent.UI.Elements;
using Terraria.Graphics;
using Terraria.Localization;
using Terraria.UI;

namespace Terraria.ModLoader.UI
{
	// Token: 0x0200029D RID: 669
	internal class UIModDownloadItem : UIPanel
	{
		// Token: 0x170001C7 RID: 455
		// (get) Token: 0x06001ABA RID: 6842 RVA: 0x00013280 File Offset: 0x00011480
		private bool HasModIcon
		{
			get
			{
				return this.modIconURL != null;
			}
		}

		// Token: 0x170001C8 RID: 456
		// (get) Token: 0x06001ABB RID: 6843 RVA: 0x0001328B File Offset: 0x0001148B
		private float ModIconAdjust
		{
			get
			{
				if (!this.modIconAppended)
				{
					return 0f;
				}
				return 85f;
			}
		}

		// Token: 0x06001ABC RID: 6844 RVA: 0x0042B504 File Offset: 0x00429704
		public UIModDownloadItem(string displayname, string name, string version, string author, string modreferences, ModSide modside, string modIconURL, string download, int downloads, int hot, string timeStamp, bool update, bool updateIsDowngrade, LocalMod installed)
		{
			this.displayname = displayname;
			this.mod = name;
			this.version = version;
			this.author = author;
			this.modreferences = modreferences;
			this.modside = modside;
			this.modIconURL = modIconURL;
			this.download = download;
			this.downloads = downloads;
			this.hot = hot;
			this.timeStamp = timeStamp;
			this.update = update;
			this.updateIsDowngrade = updateIsDowngrade;
			this.installed = installed;
			this.BorderColor = new Color(89, 116, 213) * 0.7f;
			this.dividerTexture = TextureManager.Load("Images/UI/Divider");
			this.innerPanelTexture = TextureManager.Load("Images/UI/InnerPanelBackground");
			this.Height.Set(90f, 0f);
			this.Width.Set(0f, 1f);
			base.SetPadding(6f);
			this.left = (this.HasModIcon ? 85f : 0f);
			string text = displayname + " " + version;
			this.modName = new UIText(text, 1f, false);
			this.modName.Left.Set(this.left + 5f, 0f);
			this.modName.Top.Set(5f, 0f);
			base.Append(this.modName);
			this.moreInfoButton = new UITextPanel<string>(Language.GetTextValue("tModLoader.ModsMoreInfo"), 1f, false);
			this.moreInfoButton.Width.Set(100f, 0f);
			this.moreInfoButton.Height.Set(30f, 0f);
			this.moreInfoButton.Left.Set(this.left, 0f);
			this.moreInfoButton.Top.Set(40f, 0f);
			this.moreInfoButton.PaddingTop -= 2f;
			this.moreInfoButton.PaddingBottom -= 2f;
			this.moreInfoButton.OnMouseOver += UICommon.FadedMouseOver;
			this.moreInfoButton.OnMouseOut += UICommon.FadedMouseOut;
			this.moreInfoButton.OnClick += this.RequestMoreinfo;
			base.Append(this.moreInfoButton);
			if (update || installed == null)
			{
				this.updateButton = new UITextPanel<string>(this.update ? (updateIsDowngrade ? Language.GetTextValue("tModLoader.MBDowngrade") : Language.GetTextValue("tModLoader.MBUpdate")) : Language.GetTextValue("tModLoader.MBDownload"), 1f, false);
				this.updateButton.CopyStyle(this.moreInfoButton);
				this.updateButton.Width.Set(this.HasModIcon ? 120f : 200f, 0f);
				this.updateButton.Left.Set(this.moreInfoButton.Width.Pixels + this.moreInfoButton.Left.Pixels + 5f, 0f);
				this.updateButton.OnMouseOver += UICommon.FadedMouseOver;
				this.updateButton.OnMouseOut += UICommon.FadedMouseOut;
				this.updateButton.OnClick += this.DownloadMod;
				base.Append(this.updateButton);
			}
			if (modreferences.Length > 0)
			{
				Texture2D texture = Texture2D.FromStream(Main.instance.GraphicsDevice, Assembly.GetExecutingAssembly().GetManifestResourceStream("Terraria.ModLoader.UI.ButtonExclamation.png"));
				UIHoverImage uihoverImage = new UIHoverImage(texture, Language.GetTextValue("tModLoader.MBClickToViewDependencyMods", string.Join("\n", from x in modreferences.Split(new char[]
				{
					','
				})
				select x.Trim())));
				uihoverImage.Left.Set(-149f, 1f);
				uihoverImage.Top.Set(48f, 0f);
				uihoverImage.OnClick += delegate(UIMouseEvent s, UIElement e)
				{
					UIModDownloadItem uimodDownloadItem = (UIModDownloadItem)e.Parent;
					Interface.modBrowser.SpecialModPackFilter = (from x in uimodDownloadItem.modreferences.Split(new char[]
					{
						','
					})
					select x.Trim()).ToList<string>();
					Interface.modBrowser.SpecialModPackFilterTitle = Language.GetTextValue("tModLoader.MBFilterDependencies");
					Interface.modBrowser.filterTextBox.currentString = "";
					Interface.modBrowser.updateNeeded = true;
					Main.PlaySound(10, -1, -1, 1, 1f, 0f);
				};
				base.Append(uihoverImage);
			}
			base.OnDoubleClick += this.RequestMoreinfo;
		}

		// Token: 0x06001ABD RID: 6845 RVA: 0x0042B970 File Offset: 0x00429B70
		public override int CompareTo(object obj)
		{
			UIModDownloadItem uimodDownloadItem = obj as UIModDownloadItem;
			switch (Interface.modBrowser.sortMode)
			{
			case ModBrowserSortMode.DisplayNameAtoZ:
				return string.Compare(this.displayname, (uimodDownloadItem != null) ? uimodDownloadItem.displayname : null, StringComparison.Ordinal);
			case ModBrowserSortMode.DisplayNameZtoA:
				return -1 * string.Compare(this.displayname, (uimodDownloadItem != null) ? uimodDownloadItem.displayname : null, StringComparison.Ordinal);
			case ModBrowserSortMode.DownloadsDescending:
				return -1 * this.downloads.CompareTo((uimodDownloadItem != null) ? new int?(uimodDownloadItem.downloads) : null);
			case ModBrowserSortMode.DownloadsAscending:
				return this.downloads.CompareTo((uimodDownloadItem != null) ? new int?(uimodDownloadItem.downloads) : null);
			case ModBrowserSortMode.RecentlyUpdated:
				return -1 * string.Compare(this.timeStamp, (uimodDownloadItem != null) ? uimodDownloadItem.timeStamp : null, StringComparison.Ordinal);
			case ModBrowserSortMode.Hot:
				return -1 * this.hot.CompareTo((uimodDownloadItem != null) ? new int?(uimodDownloadItem.hot) : null);
			default:
				return base.CompareTo(obj);
			}
		}

		// Token: 0x06001ABE RID: 6846 RVA: 0x0042BA88 File Offset: 0x00429C88
		public override bool PassFilters()
		{
			if (Interface.modBrowser.SpecialModPackFilter != null && !Interface.modBrowser.SpecialModPackFilter.Contains(this.mod))
			{
				return false;
			}
			if (Interface.modBrowser.filter.Length > 0)
			{
				if (Interface.modBrowser.searchFilterMode == SearchFilter.Author)
				{
					if (this.author.IndexOf(Interface.modBrowser.filter, StringComparison.OrdinalIgnoreCase) == -1)
					{
						return false;
					}
				}
				else if (this.displayname.IndexOf(Interface.modBrowser.filter, StringComparison.OrdinalIgnoreCase) == -1)
				{
					return false;
				}
			}
			if (Interface.modBrowser.modSideFilterMode != ModSideFilter.All && this.modside != (ModSide)(Interface.modBrowser.modSideFilterMode - 1))
			{
				return false;
			}
			switch (Interface.modBrowser.updateFilterMode)
			{
			default:
				return true;
			case UpdateFilter.Available:
				return this.update || this.installed == null;
			case UpdateFilter.UpdateOnly:
				return this.update;
			}
		}

		// Token: 0x06001ABF RID: 6847 RVA: 0x0042BB6C File Offset: 0x00429D6C
		protected override void DrawSelf(SpriteBatch spriteBatch)
		{
			base.DrawSelf(spriteBatch);
			if (this.HasModIcon && !this.modIconWanted)
			{
				this.modIconWanted = true;
			}
			CalculatedStyle innerDimensions = base.GetInnerDimensions();
			Vector2 vector = new Vector2(innerDimensions.X + 5f + this.ModIconAdjust, innerDimensions.Y + 30f);
			spriteBatch.Draw(this.dividerTexture, vector, null, Color.White, 0f, Vector2.Zero, new Vector2((innerDimensions.Width - 10f - this.ModIconAdjust) / 8f, 1f), SpriteEffects.None, 0f);
			vector = new Vector2(innerDimensions.X + innerDimensions.Width - 125f, innerDimensions.Y + 45f);
			this.DrawPanel(spriteBatch, vector, 125f);
			this.DrawTimeText(spriteBatch, vector + new Vector2(0f, 2f), 125);
		}

		// Token: 0x06001AC0 RID: 6848 RVA: 0x0042BC64 File Offset: 0x00429E64
		public override void Update(GameTime gameTime)
		{
			base.Update(gameTime);
			if (this.modIconWanted && !this.modIconRequested)
			{
				this.modIconRequested = true;
				using (WebClient webClient = new WebClient())
				{
					webClient.DownloadDataCompleted += this.IconDownloadComplete;
					webClient.DownloadDataAsync(new Uri(this.modIconURL));
				}
			}
			if (this.modIconReady)
			{
				this.modIconReady = false;
				this.modIconAppended = true;
				base.Append(this.modIcon);
			}
		}

		// Token: 0x06001AC1 RID: 6849 RVA: 0x0042BCF8 File Offset: 0x00429EF8
		private void IconDownloadComplete(object sender, DownloadDataCompletedEventArgs e)
		{
			try
			{
				byte[] result = e.Result;
				using (MemoryStream memoryStream = new MemoryStream(result))
				{
					Texture2D texture = Texture2D.FromStream(Main.instance.GraphicsDevice, memoryStream);
					this.modIcon = new UIImage(texture);
					this.modIcon.Left.Set(0f, 0f);
					this.modIcon.Top.Set(0f, 0f);
					this.modIconReady = true;
					this.modIconWanted = false;
				}
			}
			catch (Exception)
			{
				this.modIconReady = false;
				this.modIconWanted = false;
				this.modName.Left.Set(5f, 0f);
				this.moreInfoButton.Left.Set(0f, 0f);
				this.updateButton.Left.Set(this.moreInfoButton.Width.Pixels + 5f, 0f);
			}
		}

		// Token: 0x06001AC2 RID: 6850 RVA: 0x0042BE0C File Offset: 0x0042A00C
		protected override void DrawChildren(SpriteBatch spriteBatch)
		{
			base.DrawChildren(spriteBatch);
			if (this.modName.IsMouseHovering)
			{
				string textValue = Language.GetTextValue("tModLoader.ModsByline", this.author);
				float x = Main.fontMouseText.MeasureString(textValue).X;
				Vector2 vector = Main.MouseScreen + new Vector2(16f);
				if (vector.Y > (float)(Main.screenHeight - 30))
				{
					vector.Y = (float)(Main.screenHeight - 30);
				}
				if (vector.X > (float)Main.screenWidth - x)
				{
					vector.X = (float)Main.screenWidth - x - 30f;
				}
				Utils.DrawBorderStringFourWay(spriteBatch, Main.fontMouseText, textValue, vector.X, vector.Y, new Color((int)Main.mouseTextColor, (int)Main.mouseTextColor, (int)Main.mouseTextColor, (int)Main.mouseTextColor), Color.Black, Vector2.Zero, 1f);
			}
		}

		// Token: 0x06001AC3 RID: 6851 RVA: 0x0042BEF0 File Offset: 0x0042A0F0
		private void DrawPanel(SpriteBatch spriteBatch, Vector2 position, float width)
		{
			spriteBatch.Draw(this.innerPanelTexture, position, new Rectangle?(new Rectangle(0, 0, 8, this.innerPanelTexture.Height)), Color.White);
			spriteBatch.Draw(this.innerPanelTexture, new Vector2(position.X + 8f, position.Y), new Rectangle?(new Rectangle(8, 0, 8, this.innerPanelTexture.Height)), Color.White, 0f, Vector2.Zero, new Vector2((width - 16f) / 8f, 1f), SpriteEffects.None, 0f);
			spriteBatch.Draw(this.innerPanelTexture, new Vector2(position.X + width - 8f, position.Y), new Rectangle?(new Rectangle(16, 0, 8, this.innerPanelTexture.Height)), Color.White);
		}

		// Token: 0x06001AC4 RID: 6852 RVA: 0x0042BFD4 File Offset: 0x0042A1D4
		private void DrawTimeText(SpriteBatch spriteBatch, Vector2 drawPos, int baseWidth)
		{
			if (this.timeStamp == "0000-00-00 00:00:00")
			{
				return;
			}
			try
			{
				DateTime yourDate = DateTime.Parse(this.timeStamp);
				string text = TimeHelper.HumanTimeSpanString(yourDate);
				int num = (int)Main.fontMouseText.MeasureString(text).X;
				int num2 = baseWidth - num;
				drawPos.X += (float)num2 * 0.5f;
				Utils.DrawBorderString(spriteBatch, text, drawPos, Color.White, 1f, 0f, 0f, -1);
			}
			catch
			{
			}
		}

		// Token: 0x06001AC5 RID: 6853 RVA: 0x000132A0 File Offset: 0x000114A0
		public override void MouseOver(UIMouseEvent evt)
		{
			base.MouseOver(evt);
			this.BackgroundColor = new Color(73, 94, 171);
			this.BorderColor = new Color(89, 116, 213);
		}

		// Token: 0x06001AC6 RID: 6854 RVA: 0x0042C064 File Offset: 0x0042A264
		public override void MouseOut(UIMouseEvent evt)
		{
			base.MouseOut(evt);
			this.BackgroundColor = new Color(63, 82, 151) * 0.7f;
			this.BorderColor = new Color(89, 116, 213) * 0.7f;
		}

		// Token: 0x06001AC7 RID: 6855 RVA: 0x0042C0B4 File Offset: 0x0042A2B4
		internal void DownloadMod(UIMouseEvent evt, UIElement listeningElement)
		{
			Main.PlaySound(12, -1, -1, 1, 1f, 0f);
			try
			{
				if (UIModBrowser.PlatformSupportsTls12)
				{
					ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
				}
				using (WebClient webClient = new WebClient())
				{
					ServicePointManager.ServerCertificateValidationCallback = ((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) => true);
					Interface.modBrowser.selectedItem = this;
					Interface.downloadMod.SetDownloading(this.displayname);
					Interface.downloadMod.SetCancel(new Action(webClient.CancelAsync));
					webClient.DownloadProgressChanged += delegate(object s, DownloadProgressChangedEventArgs e)
					{
						Interface.downloadMod.SetProgress(e);
					};
					webClient.DownloadFileCompleted += delegate(object s, AsyncCompletedEventArgs e)
					{
						Main.menuMode = 10007;
						if (e.Error != null)
						{
							if (!e.Cancelled)
							{
								HttpStatusCode httpStatusCode = this.GetHttpStatusCode(e.Error);
								if (httpStatusCode == HttpStatusCode.ServiceUnavailable)
								{
									Interface.errorMessage.SetMessage(Language.GetTextValue("tModLoader.MBExceededBandwidth"));
									Interface.errorMessage.SetGotoMenu(0);
									Interface.errorMessage.SetFile(ErrorLogger.LogPath);
									Main.gameMenu = true;
									Main.menuMode = 10005;
								}
								else
								{
									Interface.errorMessage.SetMessage(Language.GetTextValue("tModLoader.MBUnknownMBError"));
									Interface.errorMessage.SetGotoMenu(0);
									Interface.errorMessage.SetFile(ErrorLogger.LogPath);
									Main.gameMenu = true;
									Main.menuMode = 10005;
								}
							}
						}
						else if (!e.Cancelled)
						{
							File.Copy(ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + "temporaryDownload.tmod", ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + this.mod + ".tmod", true);
							if (!this.update)
							{
								Interface.modBrowser.aNewModDownloaded = true;
							}
							else
							{
								Interface.modBrowser.aModUpdated = true;
							}
							base.RemoveChild(this.updateButton);
						}
						File.Delete(ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + "temporaryDownload.tmod");
					};
					webClient.DownloadFileAsync(new Uri(this.download), ModLoader.ModPath + Path.DirectorySeparatorChar.ToString() + "temporaryDownload.tmod");
				}
				Main.menuMode = 10009;
			}
			catch (WebException e)
			{
				WebException e2;
				ErrorLogger.LogModBrowserException(e2);
			}
		}

		// Token: 0x06001AC8 RID: 6856 RVA: 0x0042C1EC File Offset: 0x0042A3EC
		internal void RequestMoreinfo(UIMouseEvent evt, UIElement listeningElement)
		{
			Main.PlaySound(10, -1, -1, 1, 1f, 0f);
			try
			{
				ServicePointManager.Expect100Continue = false;
				string uriString = "http://javid.ddns.net/tModLoader/moddescription.php";
				NameValueCollection data = new NameValueCollection
				{
					{
						"modname",
						this.mod
					}
				};
				using (WebClient webClient = new WebClient())
				{
					ServicePointManager.ServerCertificateValidationCallback = ((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) => true);
					webClient.UploadValuesCompleted += this.Moreinfo;
					webClient.UploadValuesAsync(new Uri(uriString), "POST", data);
				}
			}
			catch (Exception e)
			{
				ErrorLogger.LogModBrowserException(e);
			}
		}

		// Token: 0x06001AC9 RID: 6857 RVA: 0x0042C2B4 File Offset: 0x0042A4B4
		internal void Moreinfo(object sender, UploadValuesCompletedEventArgs e)
		{
			string modInfo = Language.GetTextValue("tModLoader.ModInfoProblemTryAgain");
			string url = "";
			if (!e.Cancelled)
			{
				string @string = Encoding.UTF8.GetString(e.Result);
				JObject jobject = JObject.Parse(@string);
				modInfo = (string)jobject["description"];
				url = (string)jobject["homepage"];
			}
			Interface.modInfo.SetModName(this.displayname);
			Interface.modInfo.SetModInfo(modInfo);
			Interface.modInfo.SetMod(this.installed);
			Interface.modInfo.SetGotoMenu(10007);
			Interface.modInfo.SetURL(url);
			Main.menuMode = 10008;
		}

		// Token: 0x06001ACA RID: 6858 RVA: 0x00427A1C File Offset: 0x00425C1C
		private HttpStatusCode GetHttpStatusCode(Exception err)
		{
			if (err is WebException)
			{
				WebException ex = (WebException)err;
				if (ex.Response is HttpWebResponse)
				{
					HttpWebResponse httpWebResponse = (HttpWebResponse)ex.Response;
					return httpWebResponse.StatusCode;
				}
			}
			return (HttpStatusCode)0;
		}

		// Token: 0x040017EF RID: 6127
		public string mod;

		// Token: 0x040017F0 RID: 6128
		public string displayname;

		// Token: 0x040017F1 RID: 6129
		public string version;

		// Token: 0x040017F2 RID: 6130
		public string author;

		// Token: 0x040017F3 RID: 6131
		public string modIconURL;

		// Token: 0x040017F4 RID: 6132
		private bool modIconWanted;

		// Token: 0x040017F5 RID: 6133
		private bool modIconRequested;

		// Token: 0x040017F6 RID: 6134
		private bool modIconReady;

		// Token: 0x040017F7 RID: 6135
		private bool modIconAppended;

		// Token: 0x040017F8 RID: 6136
		public string download;

		// Token: 0x040017F9 RID: 6137
		public string timeStamp;

		// Token: 0x040017FA RID: 6138
		public string modreferences;

		// Token: 0x040017FB RID: 6139
		public ModSide modside;

		// Token: 0x040017FC RID: 6140
		public int downloads;

		// Token: 0x040017FD RID: 6141
		public int hot;

		// Token: 0x040017FE RID: 6142
		private readonly Texture2D dividerTexture;

		// Token: 0x040017FF RID: 6143
		private readonly Texture2D innerPanelTexture;

		// Token: 0x04001800 RID: 6144
		private readonly UIText modName;

		// Token: 0x04001801 RID: 6145
		private readonly UITextPanel<string> updateButton;

		// Token: 0x04001802 RID: 6146
		private readonly UITextPanel<string> moreInfoButton;

		// Token: 0x04001803 RID: 6147
		private UIImage modIcon;

		// Token: 0x04001804 RID: 6148
		public bool update;

		// Token: 0x04001805 RID: 6149
		public bool updateIsDowngrade;

		// Token: 0x04001806 RID: 6150
		public LocalMod installed;

		// Token: 0x04001807 RID: 6151
		private float left;
	}
}
